import React, { Component } from 'react';
import { Link, routerRedux } from 'dva/router';
import { connect } from 'dva';

import { List, InputItem, Button, Toast, Flex,Icon,Tabs,WingBlank,WhiteSpace } from 'antd-mobile';
import { createForm } from 'rc-form';
import NavTopBar from '../../components/NavTopBar/NavTopBar';
import MyScroll from '../../components/MyScroll/MyScroll';
import { login } from './login.less';
import username from '../../assets/svg/username.svg';
import password from '../../assets/svg/password.svg';
import code from '../../assets/svg/code.svg';
import weixinsvg from '../../assets/img/weixin.svg';
import weibosvg from '../../assets/img/weibo.svg';
import qqsvg from '../../assets/img/QQ.svg';
import { apiURl } from '../../utils/common';
import { APPSECRECT,publicWXAppID,SERVER_DOMAIN, gotoLogin,gotoWechat ,gotoQuietWechat,isWechat} from '../../utils/common';

import {beLogin} from '../../utils/judgmentEquipment';


const { Item } = List;
const tabs=[
 { title: '密码登录' },
 { title: '快速登录' },
]

class Login extends Component {
  constructor(props) {
    super(props);
    this.state={
        num: 0,
        ret: [],
        countDown: 0,
        getCodeText: '获取验证码',
    }

  }

    getCode = () => {
       this.setState({
           num:this.state.num+1
       })
    }

    gotoSina = () => {
        const sinaID = '2819680771';
        localStorage.setItem('history', location.href);
        window.location.href = `https://open.weibo.cn/oauth2/authorize?client_id=${ sinaID }&redirect_uri=${encodeURIComponent(SERVER_DOMAIN)}&response_type=code`;
        // 微博获取code
        // `https://open.weibo.cn/oauth2/authorize?client_id=2819680771&redirect_uri=http%3a%2f%2fh5.changxingshucai.cn&response_type=code`
    }

    onQuickSubmit=()=>{
        const { mobile ,mobileVerify} = this.props.form.getFieldsValue();
        if (!mobile) {
            Toast.info('请输入手机号', 1.5);
            return;
        }
        if (!mobileVerify) {
            Toast.info('请输入验证码', 1.5);
            return;
        }
        this.props.dispatch({ type: 'login/quickLoginEFF', obj: { mobile,mobileVerify } }).then((r)=>{
            if (r.code == 200) {
                // this.props.dispatch({ type: 'login/cartEFF'})
                Toast.success(r.msg, 1.5, ()=>{
                    sessionStorage.setItem('token', r.ret.token);
                    localStorage.setItem('token', r.ret.token);
                    localStorage.setItem('memberId', r.ret.memberId);
                    // console.log('1111')
                    if(this.getUrlParms("callBack")!=null){
                        window.location.href=this.getUrlParms("callBack");
                    }else{
                        this.props.dispatch(routerRedux.replace({
                            pathname: '/',
                        }))
                    }
                });
            } else {
                Toast.fail(r.msg, 1.5);
            }
        });
    };
    getUrlParms=(name)=>{
        let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        let r = window.location.search.substr(1).match(reg);
        if(r!=null)
            return unescape(r[2]);
        return null;
    }
    componentWillMount(){
        if( sessionStorage.getItem('token')||localStorage.getItem('token')){
            if(this.getUrlParms("callBack")!=null){
                window.location.href=this.getUrlParms("callBack");
            }else{
                this.props.dispatch(routerRedux.replace({
                    pathname: '/',
                }))
            }
        }
    }
   wechatLogin=()=>{
       console.log(this.getUrlParms("callBack"))
       if(this.getUrlParms("callBack")!=null){
           console.log(this.getUrlParms("callBack"))
           gotoWechat(this.getUrlParms("callBack"));
       }else{
           gotoWechat();
       }
   }
  onSubmit = () => {
        const { password, username, verifyCode } = this.props.form.getFieldsValue();
        if (!username) {
          Toast.info('请输入用户名', 1.5);
          return;
        }
      if (!password) {
          Toast.info('请输入密码', 1.5);
          return;
      }
        if (!verifyCode) {
          Toast.info('请输入验证码',1.5);
          this.setState({num: ++this.state.num});
          return;
        }


        this.props.dispatch({ type: 'login/loginEFF', obj: { username, password, verifyCode } }).then((r)=>{
            // this.setState({num: ++this.state.num});

            if (r.code == 200) {
                sessionStorage.setItem('token', r.ret.token);
                localStorage.setItem('token', r.ret.token);
                beLogin();
                Toast.success(r.msg, 1.5, ()=>{
                    if(this.getUrlParms("callBack")!=null){
                        if(this.getUrlParms("callBack").indexOf("order")!=-1){
                            this.props.dispatch(routerRedux.replace({
                                pathname: '/order',
                            }))
                        }else{
                            window.location.href=this.getUrlParms("callBack");
                        }
                    }else{
                        this.props.dispatch(routerRedux.replace({
                            pathname: '/',
                        }))
                    }

                });
            } else {
                if (r.msg == '验证码错误') this.setState({num: ++this.state.num});
                Toast.fail(r.msg, 1.5);
            }
        });

        // loginApi.login(this.props.form.getFieldsValue()).then(result => {
        //   if (result.result == 1) {
        //     Toast.success('登录成功');
        //     // 登录成功保存 token
        //     // localStorage.setItem('token', result.data[0].token);
        //     sessionStorage.setItem('token', result.data[0].token);
        //
        //
        //     window.location.href = this.callBack || 'home.html';
        //   } else {
        //     Toast.fail(result.msg, 1.5);
        //   }
        // })
  }

  countdown = () => {
      this.timer = setInterval(() => {
          if (this.state.countDown <= 0) return clearTimeout(this.timer);
          this.setState(state => {
              return {countDown: state.countDown - 1};
          })
      }, 1000);
  }

  render() {
    const { getFieldProps, getFieldError } = this.props.form;
    const {veriFyCode=""} = this.props.login.ret;
    let { num } = this.state;
    return (
            <Flex style={{
                height:"100%",
                position: "relative"
            }} direction="column"
                  className={login}
            >

                <MyScroll style={{position: "absolute", top: '0rem', bottom: "0rem"}}>
                    <form style={{width:"85%",margin:"2rem auto",boxShadow:"0 0 .1rem .05rem #999",borderRadius:".1rem"}}>
                        <WingBlank>
                            <WhiteSpace style={{background:"#fff"}}/>
                            <Flex justify="end" style={{background:"#fff"}}>
                                <Icon type="cross" style={{color:"#999",width:".6rem",height:".6rem"}} onClick={()=>{
                                        this.props.dispatch(routerRedux.goBack())
                                }}/>
                            </Flex>
                            <Tabs tabs={tabs} initialPage={0}>
                                <List
                                    renderFooter={() => getFieldError('username') && getFieldError('username').join(',')}
                                >
                                    <InputItem
                                        {...getFieldProps('username')}
                                        clear
                                        placeholder="请输入账号"
                                    ><Icon type={username.id}/></InputItem>
                                    <InputItem {...getFieldProps('password')} placeholder="请输入密码" type="password" ><Icon type={password.id}/></InputItem>
                                    <InputItem
                                        {...getFieldProps('verifyCode')}
                                        clear onExtraClick={this.getCode}
                                        placeholder="请输入验证码"
                                        extra={
                                            <div>
                                                <img src={`${apiURl}/login/imge?num=${num}`}></img>
                                            </div>
                                        }>
                                        <Icon type={code.id}/>
                                    </InputItem>
                                    <List style={{marginTop:".3rem"}}>
                                        <Item style={{ backgroundColor: 'unset' }} extra={<Link to="/forgetPassword" style={{ color: '#777' }}>忘记密码?</Link>}><Link to="/reg" style={{ color: '#ff0036' }}>手机快速注册</Link></Item>
                                    </List>
                                    <Item style={{ backgroundColor: 'unset', marginTop: '.3rem' }}>
                                        <Button type="primary" onClick={this.onSubmit} style={{borderRadius:".5rem"}}>登录</Button>
                                    </Item>

                                </List>
                                <List
                                    renderFooter={() => getFieldError('mobile') && getFieldError('username').join(',')}
                                >
                                    <InputItem
                                        {...getFieldProps('mobile')}
                                        clear
                                        placeholder="请输入手机号"
                                    ><Icon type={username.id}/></InputItem>
                                    <InputItem
                                        {...getFieldProps('mobileVerify')}
                                        clear
                                        placeholder="请输入验证码"
                                        extra={
                                            <div>
                                                {/* <span onClick={(e)=>{
                                                    const { mobile } = this.props.form.getFieldsValue();
                                                    this.props.dispatch({ type: 'login/verifyEFF', obj: { mobile } })
                                                }} style={{color:"#ff0036"}}>获取验证码</span> */}
                                                {
                                                    this.state.countDown  <= 0 ?
                                                        <span style={{color:"#ff0036"}} onClick={()=>{
                                                            const { mobile } = this.props.form.getFieldsValue();
                                                            // console.log();

                                                            if (!mobile) return !Toast.fail('请输入您的手机号')
                                                            this.props.dispatch({ type: 'login/verifyEFF', obj:{mobile} }).then(res => {
                                                                console.warn(res, '返回的数据。。。');
                                                                if (res.code == 200) {
                                                                    this.setState({countDown: 60, getCodeText: '重新获取验证码'});
                                                                    this.countdown();
                                                                }
                                                            })
                                                        }}>{this.state.getCodeText}</span>
                                                        :
                                                        <span>{this.state.countDown}秒后重新发送</span>
                                                }
                                            </div>
                                        }>
                                        <Icon type={code.id}/>
                                    </InputItem>
                                    <List style={{marginTop:".5rem"}}>
                                        <Item style={{ backgroundColor: 'unset' }} extra={<Link to="/forgetPassword" style={{ color: '#777' }}>忘记密码?</Link>}><Link to="/reg" style={{ color: '#ff0036' }}>手机快速注册</Link></Item>
                                    </List>
                                    <Item style={{ backgroundColor: 'unset', marginTop: '.3rem' }}>
                                        <Button type="primary" onClick={this.onQuickSubmit} style={{borderRadius:".5rem"}}>登录</Button>
                                    </Item>
                                </List>
                            </Tabs>
                        </WingBlank>


                    </form>
                    {isWechat()? <Flex justify="around">
                        <div style={{border:"1px solid #333",width:"1.5rem",height:"1px"}}></div>
                        <p style={{textAlign:"center",fontSize:"30px"}}>您还可以用以下方式登录</p>
                        <div style={{border:"1px solid #333",width:"1.5rem",height:"1px"}}></div>
                    </Flex>:""}

                    {isWechat()? <Flex justify="around" style={{marginTop:".5rem", height: "2rem",paddingBottom:"1.2rem"}}>
                        <Icon type={weixinsvg.id} onClick={()=>{this.wechatLogin()}} style={{width:"1.2rem",height:"1.2rem"}}/>
                        <Icon type={qqsvg.id} style={{width:"1.2rem",height:"1.2rem"}}/>
                        <Icon type={weibosvg.id} onClick={this.gotoSina} style={{width:"1.2rem",height:"1.2rem"}}/>
                    </Flex>:""}
                </MyScroll>


            </Flex>
    );
  }
}

export default connect(({ login }) => ({ login }))(createForm()(Login));
